<template>
<div>
  <article :class="[{dHide: showMap}, $root.platformClass.topArticle]">
    <!-- 头部 -->
    <header class="headBar d-box">
      <aside class="asideBox" @click="customBack()">
        <i class="i-back"></i>
      </aside>
      <aside class="dHide asideBox" @click="backHome">
        <i class="i-close"></i>
      </aside>
      <div class="headTitle b-flex">详细信息</div>
      <aside class="asideBox">
        <a href="javascript:;" class="nextStep" @click="updateGroup"><span>完成</span></a>
      </aside>
    </header>
    <!-- 主体 -->
    <section class="">
      <ul class="groupInfo mb_10">
        <li class="d-box">
          <aside class="">考勤组名称</aside>
          <div class="b-flex ta_r detailInfo">
            <input
              class="iptName"
              placeholder="请输入考勤组名称，最多20个字"
              maxlength="20"
              v-model.trim="attendanceName"/>
          </div>
        </li>
        <li class="d-box">
          <aside class="">考勤地点</aside>
          <div class="b-flex ta_r detailInfo" @click="toggleMap">
            {{ location }}<i class="i-arr-right"></i>
          </div>
        </li>
        <li class="d-box">
          <aside class="">有效签到范围(公司打卡)</aside>
          <div class="b-flex ta_r detailInfo" @click="openSelectScopeModal('range')">
            {{ range }}米<i class="i-arr-right"></i>
          </div>
        </li>
        <li class="d-box">
          <aside class="">有效签到范围(外勤打卡)</aside>
          <div class="b-flex ta_r detailInfo" @click="openSelectScopeModal('outRange')">
            {{ outRange }}米<i class="i-arr-right"></i>
          </div>
        </li>
      </ul>
      <ul class="groupInfo mb_10">
        <li class="d-box">
          <aside class="">上午工作时间</aside>
          <div class="b-flex ta_r detailInfo">
            <div class="workTime" @click="selectTime(0)">
                <div class="timeStr" v-text="amTime1"></div>
            </div>
            -
            <div class="workTime" @click="selectTime(1)">
                <div class="timeStr" v-text="amTime2"></div>
            </div>
          </div>
        </li>
        <li class="d-box">
          <aside class="">下午工作时间</aside>
          <div class="b-flex ta_r detailInfo">
            <div class="workTime" @click="selectTime(2)">
                <div class="timeStr" v-text="pmTime1"></div>
            </div>
            -
            <div class="workTime" @click="selectTime(3)">
                <div class="timeStr" v-text="pmTime2"></div>
            </div>
          </div>
        </li>
      </ul>
      <div class="memberBox">
        <div class="memberAdd d-box" @click="setAppealAuditor">
          <aside class="">异常审批人</aside><div class="b-flex ta_r detailInfo">{{ examineName }}<i class="i-arr-right"></i></div>
        </div>
        <div class="memberAdd d-box">
          <aside class="">考勤成员</aside>
          <div class="b-flex ta_r">
            <div v-if="0" class="addBtn" @click="addMySelf">添加自己</div>
            <div class="addBtn ml_5" @click="setEmployees">添加成员</div>
          </div>
        </div>
        <ul class="memberList">
          <li class="d-box" v-for="contact in employees" @click="deleteMember(contact.euserId)">
            <div class="b-flex detailInfo">{{ contact.name + (contact.department ? '[' + contact.department + ']' : '')}}</div>
            <aside><i class="i-fork"></i></aside>
          </li>
        </ul>
      </div>
    </section>
    <!-- 引入组件 -->
    <time-select
      :select-index="timeSelectIndex"
      :show="showTimeSelect"
      mode="Time"
      :selected ="selectedTime"
      @close="onTimeSelectClose"
      @confirm="onTimeSelectionConfirm"
    ></time-select>
  </article>
  <!-- <SetCheckPoint :show="showMap" @hidePanle="toggleMap" @markPoint="updatePosition"></SetCheckPoint> -->
  <!-- 选择打卡范围 -->
  <modal :show="modalShow"
    title="请选择有效签到范围"
    summary="地图服务商获取位置时可能会有所偏差"
    mode="Alert" @close="modalClose" @alertOk="alertOk">
    <ul class="range">
      <li class="d-box" v-for="(value, key) in selectScopeValues" @click="selectScopeVal(key)">
        <div class="b-flex">{{ value }}米</div><aside><i :class="[{check: value === selectScopeValue }]"></i></aside>
      </li>
    </ul>
  </modal>
  <!-- 成员已在其他考勤组提示 -->
  <modal :show="modalShow2" title="温馨提示"
    summary="以下成员已在其他考勤组。是否将其移动到新的考勤组？"
    mode="Alert" @close="modalClose2" @alertOk="alertOk2" containerCls="pop_move">
    <ul class="memberList pop_move">
      <li class="d-box" v-for="item in tempEmployees" v-on:click="deleteEmployeeInOtherGroup(item.euserId)">
        <div class="b-flex detailInfo">{{ item.name }}{{ item.department ? '[' + item.department + ']' : '' }}</div><aside><i class="i-fork"></i></aside>
      </li>
    </ul>
  </modal>
</div>
</template>

<script>
import TimeSelect from '../common/TimeSelect'
// import SetCheckPoint from './SetCheckPoint'
import RcsClient from '../../utils/rcsClient'
import { queryMyOwnGroup, addAttendanceGroup, updateAttendanceGroup, checkEmployee } from '@/api'
import store from '@/store/index'
import { validateGroupName, getTimeGap, mutateMinutes, debounce } from '../../utils'
import Modal from '../common/Modal'

export default {
  name: 'GroupDetail',
  components: {
    TimeSelect,
    // SetCheckPoint,
    Modal
  },
  props: ['initailGroupInfo'],
  store,
  data () {
    const initailGroupInfo = {...this.initailGroupInfo}
    const amTimeArr = initailGroupInfo.amTime.split('-')
    const pmTimeArr = initailGroupInfo.pmTime.split('-')

    initailGroupInfo.amTime1 = amTimeArr[0]
    initailGroupInfo.amTime2 = amTimeArr[1] || amTimeArr[0]
    initailGroupInfo.pmTime1 = pmTimeArr[0]
    initailGroupInfo.pmTime2 = pmTimeArr[1] || pmTimeArr[0]
    delete initailGroupInfo.amTime
    delete initailGroupInfo.pmTime

    // alert(JSON.stringify(this.initailGroupInfo))
    return Object.assign({
      attendanceId: '',
      attendanceName: '',
      enterId: '',
      enterName: '',
      amTime1: '08:30',
      amTime2: '11:30',
      pmTime1: '13:00',
      pmTime2: '17:30',
      location: '',
      detailAddr: '',
      longitude: '',
      latitude: '',
      range: '2000',
      rangeValues: ['50', '100', '200', '300', '500', '1000', '1500', '2000'],
      outRange: '2000',
      outRangeValues: ['50', '100', '200', '300', '500', '1000', '1500', '2000'],
      selectScopeField: '',
      selectScopeValue: '',
      selectScopeValues: [],
      employees: [],
      showTimeSelect: false,
      timeSelectIndex: 0,
      timeSelectStart: '',
      timeSelectEnd: '',
      selectedTime: '',
      showMap: false,
      rcsClient: new RcsClient(),
      // 以下是范围选择组件数据
      modalShow: false,
      // 以下是员工已在其他考勤组提示数据
      modalShow2: false,
      tempEmployees: [],
      examineName: '',
      examineUid: '',
      examineEUserId: '',
      selectorField: ''
    }, initailGroupInfo)
  },
  mounted () {
    // 打通vue与rcs注入的方法
    this.rcsClient.linkToRcs(this)
  },
  computed: {
    amTime () {
      return this.amTime1 + '-' + this.amTime2
    },
    pmTime () {
      return this.pmTime1 + '-' + this.pmTime2
    },
    updateInfo () {
      return {
        attendanceName: this.attendanceName,
        enterId: this.enterId,
        enterName: this.enterName,
        amTime: this.amTime,
        pmTime: this.pmTime,
        location: this.location,
        detailAddr: this.detailAddr,
        longitude: this.longitude,
        latitude: this.latitude,
        range: this.range,
        outRange: this.outRange,
        employees: this.employees,
        examineName: this.examineName,
        examineUid: this.examineUid,
        examineEUuserid: this.examineEUuserid
      }
    }
  },
  watch: {
    initailGroupInfo () {
      const amTimeArr = this.initailGroupInfo.amTime.split('-')
      const pmTimeArr = this.initailGroupInfo.pmTime.split('-')

      // 初始化外勤搜索范围
      this.initailGroupInfo.outRange = this.initailGroupInfo.outRange === '0' ? '500' : this.initailGroupInfo.outRange

      Object.assign(this.$data, {
        ...this.$props.initailGroupInfo,
        amTime1: amTimeArr[0],
        amTime2: amTimeArr[1] || amTimeArr[0],
        pmTime1: pmTimeArr[0],
        pmTime2: pmTimeArr[1] || pmTimeArr[0]
      })
    }
  },
  methods: {
    selectTime (index) {
      const timeRange = [
        {
          field: 'amTime1',
          start: '00:00',
          end: this.amTime2 || this.pmTime1 || this.pmTime2 || '23:59'
        },
        {
          field: 'amTime2',
          start: this.amTime1 || '00:00',
          end: this.pmTime1 || this.pmTime2 || '23:59'
        },
        {
          field: 'pmTime1',
          start: this.amTime1 || this.amTime2 || '00:00',
          end: this.pmTime2 || '23:59'
        },
        {
          field: 'pmTime2',
          start: this.amTime1 || this.amTime2 || this.pmTime1 || '00:00',
          end: '23:59'
        }
      ]
      console.log('selectTime ', index)
      this.timeSelectIndex = index
      this.timeSelectStart = timeRange[index].start
      this.timeSelectEnd = timeRange[index].end
      this.selectedTime = this[timeRange[index]['field']]
      this.showTimeSelect = true
    },
    onTimeSelectClose () {
      this.showTimeSelect = !this.showTimeSelect
    },
    onTimeSelectionConfirm (time, index) {
      const fieldArr = [
        'amTime1',
        'amTime2',
        'pmTime1',
        'pmTime2'
      ]
      // 自动调整时间间隔
      const autoAdjustTime = (_time, _index) => {
        let i = 0
        let n = 0
        let timeGap = 0
        let startTime = ''
        let endTime = ''
        let minGap = 30

        // 往前调整
        for (i = _index, n = 0; i > n; i--) {
          startTime = this[fieldArr[i - 1]]
          endTime = this[fieldArr[i]]
          timeGap = getTimeGap(startTime, endTime)
          if (timeGap < minGap) {
            this[fieldArr[i - 1]] = getTimeGap('00:00', endTime) < minGap ? '00:00' : mutateMinutes(endTime, -minGap)
          }
        }
        // 往后调整
        for (i = _index, n = fieldArr.length - 1; i < n; i++) {
          startTime = this[fieldArr[i]]
          endTime = this[fieldArr[i + 1]]
          timeGap = getTimeGap(startTime, endTime)
          if (timeGap < minGap) {
            this[fieldArr[i + 1]] = getTimeGap(startTime, '24:00') < minGap ? '24:00' : mutateMinutes(startTime, minGap)
          }
        }
      }

      console.log(time, index)
      this[fieldArr[index]] = time
      autoAdjustTime(time, index)
    },
    updateMyGroupInfo () {
      const myIndex = this.employees.findIndex((contact) => {
        return (contact.enterpriseId + '') === this.$root.userInfo.enterpriseId
      })

      if (myIndex > -1) {
        // 获取自己的最新的考勤组数据
        queryMyOwnGroup({}, (err, data) => {
          if (err) {
            console.error(err)
            return false
          } else {
            this.$root.setMyGroupInfo(data['var'])
            this.$store.dispatch('fetchUserOwnInfo', data['var'])
          }
        })
      }
    },
    doPost () {
      const editMode = this.$route.name === 'EditGroup'
      const groupInfo = editMode ? { ...this.updateInfo, attendanceId: this.attendanceId + '' } : this.updateInfo
      const apiConfig = {
        'AddGroupStepTwo': { api: addAttendanceGroup, msg: '考勤组创建成功' },
        'EditGroup': { api: updateAttendanceGroup, msg: '考勤组信息已保存' }
      }
      const serverAPI = apiConfig[this.$route.name].api
      if (groupInfo.employees.length === 0) {
        this.showTip('请添加考勤组成员')
        return false
      }

      if (groupInfo.attendanceName.length === 0) {
        this.showTip('考勤组名称不能为空')
        return false
      }

      if (groupInfo.location.length === 0) {
        this.showTip('请设置考勤地点')
        return false
      }

      // 编辑模式
      if (!editMode) {
        validateGroupName({ enterId: groupInfo.enterId, groupName: groupInfo.attendanceName }, duplicated => {
          if (duplicated) {
            this.showTip('已存在相同的考勤组名称!')
            return false
          } else {
            serverAPI(groupInfo, (err, data) => {
              if (err) {
                console.log(err)
                this.showTip(err.summary || err.msg)
                return false
              }
              this.showTip(apiConfig[this.$route.name].msg)
              // this.updateMyGroupInfo()
              this.$router.replace({name: 'GroupList'})
            })
          }
        })
      } else {
        serverAPI(groupInfo, (err, data) => {
          if (err) {
            console.log(err)
            this.showTip(err.summary || err.msg)
            return false
          }
          this.showTip(apiConfig[this.$route.name].msg)
          // this.updateMyGroupInfo()
          this.$router.replace({name: 'GroupList'})
        })
      }
    },
    updateGroup: debounce(function () {
      // alert('提交考勤组信息')
      // alert(JSON.stringify(this.updateInfo))
      const editMode = this.$route.name === 'EditGroup'
      const groupInfo = editMode ? {...this.updateInfo, attendanceId: this.attendanceId + ''} : this.updateInfo

      if (groupInfo.employees.length === 0) {
        this.showTip('请添加考勤组成员')
        return false
      }

      if (groupInfo.attendanceName.length === 0) {
        this.showTip('考勤组名称不能为空')
        return false
      }

      if (groupInfo.location.length === 0) {
        this.showTip('请设置考勤地点')
        return false
      }

      if ((getTimeGap(this.amTime1, this.amTime2) < 1) || (getTimeGap(this.pmTime1, this.pmTime2) < 1)) {
        this.showTip('结束时间要大于开始时间!')
        return false
      }

      // 检测考勤组成员先前的考勤组关系
      checkEmployee({
        'employees': groupInfo.employees,
        'attendanceId': this.attendanceId
      }, (err, data) => {
        if (err) {
          console.log(err)
          this.showTip(err)
          return false
        }
        const members = data['var']
        const employees = groupInfo.employees
        // 筛选出已在其他考勤组的成员
        const tempEmployees = employees.reduce((acc, item, index) => {
          return members[index].attendanceId > 0 ? acc.concat([employees[index]]) : acc
        }, [])

        if (tempEmployees.length > 0) {
          this.tempEmployees = tempEmployees
          this.modalShow2 = true
        } else {
          this.doPost()
        }
      })
    }, 3000, {leading: true, trailing: false}),
    customBack () {
      if (this.$route.name === 'AddGroupStepTwo') {
        this.showConfirm(
          '考勤组信息尚未保存,是否要重新开始新建考勤组？',
          // 取消
          () => {

          },
          // 确定
          () => {
            this.$router.replace({name: 'AddGroupStepOne'})
            this.$root.resetNewGroupInfo()
          }
        )
        return false
      }

      if (this.$route.name === 'EditGroup') {
        this.$router.back()
        return false
      }
    },
    addMember () {
      try {
        this.rcsClient.call('selectEnterpriseContactMulti', '多选', 500, this.rcsClient.getRcsBackId(), 'rcsCallBack', JSON.stringify(this.employees))
      } catch (e) {
        console.log(e)
      }
    },
    addMySelf () {
      const myIndex = this.employees.findIndex(item => { return item.id === this.$root.userInfo.id })
      if (myIndex > -1) {
        this.employees.splice(myIndex, 1)
      } else {
        this.employees.splice(0, 0, this.$root.userInfo)
      }
    },
    deleteMember (euserId) {
      const myIndex = this.employees.findIndex(item => { return item.euserId === euserId })
      this.employees.splice(myIndex, 1)
    },
    toggleMap () {
      this.showMap = !this.showMap
    },
    updatePosition ({location, detailAddr, longitude, latitude}) {
      this.location = location
      this.detailAddr = detailAddr
      this.longitude = longitude
      this.latitude = latitude
    },
    rcsCallBack: function (apiName, ...params) {
      this[apiName + 'CB'] && this[apiName + 'CB'](...params)
    },
    selectEnterpriseContactMultiCB (backId, contactInfo) {
      // 和飞信人员选择器支持跨企业选择
      // 需要过滤掉跨企业的用户
      this.employees = contactInfo
      // this.employees = contactInfo.filter((contact) => {
      //   return (contact.enterpriseId + '') === this.$root.userInfo.enterpriseId
      // })

      // if (contactInfo.length > this.employees.length) {
      //   this.showTip('已过滤掉跨企业的用户!')
      //   this.showTip('已过滤掉跨企业的用户!')
      // }
    },
    getRCSTokenCB ({backId, status, token}) {
      const filedConfig = {
        'examineName': (data) => {
          const user = data[0]
          // alert(JSON.stringify(user, 1, 4))
          this.examineName = user.name
          this.examineUid = user.euserId || user.contactId
          this.examineEUuserid = user.euserId
        },
        'employees': (data) => {
          // 容错处理,去掉euserId重复的人员
          this.employees = data.reduce((acc, item) => {
            return !acc.find(_item => item.euserId === _item.euserId) ? acc.concat(item) : acc
          }, [])
        }
      }
      const multiSelect = (this.selectorField === 'employees')
      // const img1 = new Image()
      // img1.src = 'img?rcstoken=' + token + '&' + window.document.cookie.replace(/;\s/g, '&')

      this.openSelector({
        token,
        selectArray: multiSelect ? this.employees : [{contactId: this.examineUid, enterpriseId: this.enterId, name: this.examineName}],
        multiSelect: multiSelect,
        callback: (res) => {
          if (res.result === 0) {
            filedConfig[this.selectorField] && filedConfig[this.selectorField](res.data)
          } else if (res.result === 1) {
            // 触发取消按钮
          } else {
            this.showTip('选择器数据异常')
          }
        }
      })
    },
    setAppealAuditor () {
      this.selectorField = 'examineName'
      this.rcsClient.call('getRCSToken', {backId: this.rcsClient.getRcsBackId(), backFunc: 'rcsCallBack'})
    },
    setEmployees () {
      this.selectorField = 'employees'
      this.rcsClient.call('getRCSToken', {backId: this.rcsClient.getRcsBackId(), backFunc: 'rcsCallBack'})
    },
    modalClose () {
      this.modalShow = false
      this.selectScopeVal(this.range)
    },
    alertOk () {
      this[this.selectScopeField] = this.selectScopeValue
      this.modalShow = false
    },
    openSelectScopeModal (field) {
      // let selectScopeValues = JSON.parse(JSON.stringify(this.selectScopeValues))
      // for (let i in selectScopeValues) {
      //   selectScopeValues[i] = false
      // }
      // selectScopeValues[this.range] = true
      // this.modalShow = true

      this.selectScopeField = field
      this.selectScopeValue = this[field]
      this.selectScopeValues = this[field + 'Values']
      this.modalShow = true
    },
    selectScopeVal (key) {
      this.selectScopeValue = this.selectScopeValues[key]
    },
    // 以下是已在其他考勤组员工提示方法
    modalClose2 () {
      this.modalShow2 = false // 关闭弹窗
      this.tempEmployees = []
    },
    alertOk2 () {
      this.modalShow2 = false  // 关闭弹窗
      this.doPost()
    },
    deleteEmployeeInOtherGroup (euserId) {
      let _employees = this.employees
      let employees = []
      let _tempEmployees = this.tempEmployees
      let tempEmployees = []
      employees = _employees.filter(value => {
        return value.euserId !== euserId
      })
      tempEmployees = _tempEmployees.filter(value => {
        return value.euserId !== euserId
      })
      this.employees = employees
      this.tempEmployees = tempEmployees
      console.log('this.employees => \n', JSON.stringify(employees))
    }
  }
}
</script>
